from inspect import getgeneratorstate


class DemoException(Exception):
    """for test """


def demo_exc_handling():
    print('-> coroutine started')

    while True:
        try:
            x = yield
        except DemoException:
            print('*** DemoException handled. Continuing...')
        else:
            print('-> coroutine received:{!r}'.format(x))

    raise RuntimeError('This line should never run.')


if __name__ == '__main__':
    # 常规用法
    exc_coro = demo_exc_handling()
    next(exc_coro)
    exc_coro.send(11)
    exc_coro.send(22)
    exc_coro.close()
    print(getgeneratorstate(exc_coro))
    # 传入DemoException
    exc_coro = demo_exc_handling()
    next(exc_coro)
    exc_coro.send(11)
    exc_coro.throw(DemoException)
    print(getgeneratorstate(exc_coro))
    exc_coro.close()
    print(getgeneratorstate(exc_coro))
    # 传入没处理的异常 协程终止
    exc_coro = demo_exc_handling()
    next(exc_coro)
    exc_coro.send(11)
    # exc_coro.throw(ZeroDivisionError)
    # print(getgeneratorstate(exc_coro))
